package com.zheng.common.util;

import com.zheng.common.constant.Constant;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 生成随机数字码工具类
 * Created by admin on 2016/5/4.
 */
public class RandomNumUtils {

    private static Object lock = new Object();

    private static RandomNumUtils instance;

    private Map<String, Long> randomNumberMap = new ConcurrentHashMap<String, Long>();

    private static final String[] BASE_NUMBER = new String[]{
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
    };

    private static final int RANDOM_STRING_LENGTH = 4;

    private RandomNumUtils() {
    }

    public static RandomNumUtils getInstance() {
        synchronized (lock) {
            if (instance == null) {
                instance = new RandomNumUtils();
            }
        }
        return instance;
    }

    public String getRandomNum() {
        Long nowTime = System.currentTimeMillis();
        String randomNum = null;

        synchronized (lock) {
            // 生成随机数字串
            randomNum = createRandomNum(RANDOM_STRING_LENGTH, nowTime);

            // 删除一分钟前的随机数字串
            Iterator<Map.Entry<String, Long>> it = randomNumberMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Long> entry = it.next();
                Long value = entry.getValue();
                if (nowTime - value > Constant.RPC_SEQ_NO_NOT_REPEAT_INTERVAL) {
                    it.remove();
                }
            }
        }

        return randomNum;
    }

    private String createRandomNum(int len, Long nowTime) {
        Random random = new Random();
        int length = BASE_NUMBER.length;
        String randomString = "";
        for (int i = 0; i < length; i++) {
            randomString += BASE_NUMBER[random.nextInt(length)];
        }
        random = new Random(System.currentTimeMillis());
        String resultStr = "";
        for (int i = 0; i < len; i++) {
            resultStr += randomString.charAt(random.nextInt(randomString.length() - 1));
        }

        // 判断一分钟内是否重复
        Long randomStrCreateTime = randomNumberMap.get(resultStr);
        if (randomStrCreateTime != null &&
                nowTime - randomStrCreateTime < Constant.RPC_SEQ_NO_NOT_REPEAT_INTERVAL) {
            resultStr = createRandomNum(len, nowTime);
        }
        randomNumberMap.put(resultStr, nowTime);
        return resultStr;
    }

}
